package vip.zhenzicheng.test.juc.atomic;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;

/**
 * @author zhenzicheng
 * @date 2022-09-07 09:16
 */
public class AtomicReferenceFieldUpdaterCase {

  public static void main(String[] args) {
    MyVar myVar = new MyVar();
    for (int i = 0; i < 10; i++) {
      new Thread(() -> myVar.init(myVar), String.valueOf(i)).start();
    }
  }
}

@Slf4j
class MyVar {

  static final AtomicReferenceFieldUpdater<MyVar, Boolean> referenceFieldUpdater =
    AtomicReferenceFieldUpdater.newUpdater(MyVar.class, Boolean.class, "isInit");
  public volatile Boolean isInit = Boolean.FALSE;

  public void init(MyVar myVar) {
    if (referenceFieldUpdater.compareAndSet(myVar, Boolean.FALSE, Boolean.TRUE)) {
      log.info("当前线程: {} ---- start init", Thread.currentThread().getName());
      try {
        TimeUnit.SECONDS.sleep(2);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      log.info("当前线程: {} ---- over init", Thread.currentThread().getName());
    } else {
      log.info("初始化失败，已经在初始化");
    }
  }
}